<?php

declare(strict_types=1);

namespace app\admin\service\shop;

use app\api\lib\SuPengJun;
use app\api\lib\Wechat;
use app\api\service\OrderService as ApiOrderService;
use app\common\model\dynamic\DynamicModel;
use app\common\model\NoticeModel;
use app\common\model\order\OrderGoodsModel;
use app\common\model\order\OrderRefundModel;
use app\common\model\system\ExpressModel;
use app\common\model\user\UserModel;
use app\common\service\ConfigService;
use Dengje\Pxy\BaseService;

class OrderService extends BaseService
{
    protected $model = null;


    public function __construct()
    {
        $this->model =  new \app\common\model\order\OrderModel();
    }

    public function list()
    {
        $where[] = ['type', '=', 0];
        $type = request()->get('type', 0);
        if ($type == 1) {
            $where[] = ['pay_status', '=', 0];
            $where[] = ['status', '=', 1];
        } else if ($type == 2) {
            $where[] = ['pay_status', 'in', [0, 1, 2, 3]];
            $where[] = ['status', '=', 2];
        } else if ($type == 3) {
            $where[] = ['pay_status', 'in', [0, 1, 2, 3]];
            $where[] = ['status', '=', 3];
        } else if ($type == 4) {
            $where[] = ['pay_status', 'in', [0, 1, 2, 3]];
            $where[] = ['status', '=', 4];
        } else if ($type == 5) {
            $where[] = ['pay_status', 'in', [2, 3, 4]];
            $where[] = ['status', '<>', 0];
        } else if ($type == 6) {
            $where[] = ['status', '=', 6];
        }
        $order_no = request()->get('order_no', 0);
        $user_id = request()->get('user_id', 0);
        if ($order_no) $where[] = ['order_no', '=', $order_no];
        if ($user_id) $where[] = ['user_id', '=', $user_id];
        $list = $this->model->where($where)->order(['id' => 'desc'])->paginate(request()->get('page_size/d', 10));
        $list->map(function ($v) {
            $v['user'] = UserModel::where('id', $v['user_id'])->field('name,avatar')->find();
            $v['status_str'] = ApiOrderService::status_str($v['pay_status'], $v['status']);
            $v['payment_time_str'] = $v['payment_time'] ? date('Y-m-d H:i:s', $v['payment_time']) : '无';
            $v['ship_time_str'] = $v['ship_time'] ? date('Y-m-d H:i:s', $v['ship_time']) : '无';
            $v['confirm_time_str'] = $v['confirm_time'] ? date('Y-m-d H:i:s', $v['confirm_time']) : '无';
            $v['refund'] = OrderRefundModel::where('order_id', $v['id'])->where('status', 0)->count();
            return $v;
        });
        return $list;
    }

    public function detail($id, $data)
    {
        $detail = $this->model->where('id', $id)->find();
        if ($data['type'] == 1) {
            $detail['goods'] = OrderGoodsModel::where('order_id', $id)
                ->append(['visible'])
                ->withAttr('visible', function () {
                    return false;
                })
                ->select();
        } else if ($data['type'] == 2) {
            $detail['refund'] = OrderRefundModel::where('order_id', $id)->select();
        }
        return $detail;
    }

    public function update($id, $data)
    {
        $data = $this->preExcludeFields($data);
        unset($data['goods']);
        return $this->model->where('id', $id)->update($data);
    }

    public function refpay($id, $data)
    {
        $data = $this->preExcludeFields($data);
        if ($data['refund_price'] && $data['refund_price'] > 0) {
            if (!$data['can_refund_price'] || $data['can_refund_price'] <= 0) return error('订单可退款金额不足！');
            if ($data['refund_price'] > $data['can_refund_price']) return error('退款金额不能大于订单可退款金额！');
            $out_refund_no = SuPengJun::getSn(4);
            (new OrderRefundModel())->insert([
                'refund_no' => $out_refund_no,
                'refund_reason' => '后台操作订单退款',
                'refund_price' => $data['refund_price'],
                'order_id' => $id,
                'status' => 1,
                'create_time' => time(),
            ]);
            $result = (new Wechat())->refund($data['serial_number'], $out_refund_no, $data['payed'], $data['refund_price']);
            if ($result['code'] != 1) return error('处理失败！' . $result['msg']);
        }
        return $out_refund_no;
    }

    public function delete($id)
    {
        $this->model->where('id', $id)->delete();
        OrderGoodsModel::where('order_id', $id)->delete();
        OrderRefundModel::where('order_id', $id)->delete();
        DynamicModel::where('order_id', $id)->update(['order_id' => '']);
        return success('删除成功！');
    }

    public function delivery($id, $data)
    {
        $data = $this->preExcludeFields($data);
        $content = '订单"' . $data['order_no'] . '"由 ' . $data['express'] . '：' . $data['express_no'] . ' 为您配送到家。';
        $goodsDiv = '';
        for ($i = 0; $i < count($data['goods']); $i++) {
            $div = '<div style="width: 100%;display: flex;align-items: center;padding-bottom: 10px;">
					<img src=' . $data['goods'][$i]['product_img'] . ' style="width: 68px;height: 68px;border-radius:4px;" />
					<div style="width: calc(100% - 78px);margin-left:10px;">
						<div style="font-size: 12px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                           ' . $data['goods'][$i]['goods_name'] . '
						</div>
						<div style="font-size: 12px;color: #999;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                           ' . $data['goods'][$i]['product_name'] . '
						</div>
						<div style="display: flex;justify-content: space-between;margin-top: 8px;">
							<div style="font-size: 11px;">×' . $data['goods'][$i]['quantity'] . ' </div>
                            <div style="font-size: 13px;">¥' . $data['goods'][$i]['product_price'] . '</div>
						</div>
					</div>
				    </div>';
            $goodsDiv = $goodsDiv . $div;
        };
        $goods = '<div style="margin-top: 10px;background: #f8f8f8;padding:10px 10px 0;border-radius:4px;color: #000000;">' . $goodsDiv . '</div>';
        $content = $content . $goods;
        (new NoticeModel())->send($data['user_id'], '订单发货通知 🚚', $content, 0, '', '/pages/order/details?id=' . $data['id'], 3);
        unset($data['goods']);
        $data['status'] = 3;
        // 发货事件
        event('admin.delivery', ['order_id' => $id]);
        return $this->model->where('id', $id)->update($data);
    }

    public function refund($id, $data)
    {
        $data = $this->preExcludeFields($data);
        $order = $this->model->where('id', $data['order_id'])->field('serial_number,payed,can_refund_price')->find();
        if ($data['refund_price'] && $data['refund_price'] > 0) {
            if (!$order['can_refund_price'] || $order['can_refund_price'] <= 0) return error('订单可退款金额不足！');
            if ($data['refund_price'] > $order['can_refund_price']) return error('退款金额不能大于订单可退款金额！');
            $result = (new Wechat())->refund($order['serial_number'], $data['refund_no'], $order['payed'], $data['refund_price']);
            if ($result['code'] != 1) return error('处理失败！' . $result['msg']);
        }
        $refundModel = ['status' => $data['status'], 'refund_price' => $data['refund_price']];
        return success('操作成功', OrderRefundModel::where('id', $data['id'])->update($refundModel));
    }

    public function edit_goods($id, $data)
    {
        $data = $this->preExcludeFields($data);
        unset($data['visible']);
        return OrderGoodsModel::where('id', $id)->update($data);
    }

    public function refund_adds($data)
    {
        $data = $this->preExcludeFields($data);
        if ($data['type'] == 1) {
            $value = implode(',', [$data['name'], $data['mobile'], $data['adds']]);
            ConfigService::set('applet', 'shop_adds', $value);
        } else {
            $value = ConfigService::get('applet', 'shop_adds');
        }
        return $value ? explode(',', $value) : [];
    }
}
